﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;
using System.Xml;
using System.Configuration;
using MES.DataGateway.Common;
using MES.DataGateway.StandardDataSync;
using MES.DataGateway.SyncEntity;
using MES.DataGateway.SyncInterface;
using MES.DataGateway.SyncContext;
using System.Windows.Forms;
using MES.DataGateway.IControlUnit;
using MES.DataGateway.ControlUnitContext;
using MES.DataGateway.StandardEntity;
using MES.DataGateway.IExtendedBuessiness;
//using MES.DataGateway.ExtendedBuessinessContext;
using MES.DataGateway.OracleDAL;
using MES.DataGateway.SyncCommon;
using MES.DataGateway.ExtendedBusiness;
using MES.DataGateway.DBUtility;
using System.Data.OracleClient;

namespace MES.DataGateway.Presenter
{
    public class DataGatwayPresenter
    {
        private List<ServiceEntity> m_ServiceList = new List<ServiceEntity>();
        private DataSet m_FileSet = new DataSet();
        private DataSet m_StandardClassSet = new DataSet();
        private ServiceDataSet m_ServiceInfoSet = new ServiceDataSet();
        private string m_strDataXml = "";
        private string m_strDataTransfer = "";
        private string m_AccessoriesPath = "";
        private string m_MainExtendedBusiness = "";
        private string m_SyncType = "1";
        private string m_ProductName = "";
        private string m_ProductVersion = "";
        private System.Threading.Thread tget;
        private List<object> m_OutInfoList = new List<object>();
        private AssistantClass m_AssistantClass = new AssistantClass();

        public List<ServiceEntity> ServiceList
        {
            get { return m_ServiceList; }
            set { m_ServiceList = value; }
        }


        #region 得到配置文件信息
        private void GetConfigSetting()
        {
            FileInfo file = new FileInfo(Application.StartupPath + "\\MES.DataGateway.Service.exe.config");

            if (!file.Exists)
            {
                throw new Exception("配置文件丢失！");
            }

            //加载config文件
            XmlDocument doc = new XmlDocument();
            doc.Load(file.FullName);

            //循环读写Web.config文件的configuration\appSettings节
            foreach (XmlNode node in doc["configuration"]["appSettings"])
            {
                if (node.Name == "add")
                {
                    if (node.Attributes.GetNamedItem("key").Value == "DataXmlPath")
                    {
                        m_strDataXml = node.Attributes.GetNamedItem("value").Value;
                    }
                    else if (node.Attributes.GetNamedItem("key").Value == "DataTransfer")
                    {
                        m_strDataTransfer = node.Attributes.GetNamedItem("value").Value;
                    }
                    else if (node.Attributes.GetNamedItem("key").Value == "AccessoriesPath")
                    {
                        m_AccessoriesPath = node.Attributes.GetNamedItem("value").Value;
                    }
                    else if (node.Attributes.GetNamedItem("key").Value == "ExtendedBusiness")
                    {
                        m_MainExtendedBusiness = node.Attributes.GetNamedItem("value").Value;
                    }
                    else if (node.Attributes.GetNamedItem("key").Value == "SyncType")
                    {
                        m_SyncType = node.Attributes.GetNamedItem("value").Value;
                    }
                }
            }
        }
        #endregion

        #region 读取注册文件列表
        private void GetFileRegisterInfo()
        {
            if (File.Exists(Application.StartupPath + "\\XML\\registerFile.xml") == true)
            {
                m_FileSet.ReadXml(Application.StartupPath + "\\XML\\registerFile.xml");
            }
            else
            {
                DataTable registerXmlTable = new DataTable();
                registerXmlTable.Columns.Add("xmlFile");
                registerXmlTable.Columns.Add("ProjectNO");
                registerXmlTable.Columns.Add("ServiceKey");
                registerXmlTable.Columns.Add("CreateDate", Type.GetType("System.String"));
                m_FileSet.Tables.Add(registerXmlTable);
            }
        }
        #endregion

        #region 读取驱动配置
        private void ReadServiceInfo()
        {
            FileInfo file = new FileInfo(Application.StartupPath + "\\MES.DataGateway.Service.exe.config");
            if (!file.Exists)
            {
                throw new Exception("配置文件丢失！");
            }

            //加载config文件
            XmlDocument doc = new XmlDocument();
            doc.Load(file.FullName);

            foreach (XmlNode node in doc["configuration"]["log4net"]["DataGateway"])
            {
                if (node.Name == "ServiceType")
                {
                    ReadServiceType(node);
                }
            }
        }

        private void ReadServiceType(XmlNode node)
        {
            ServiceDataSet.ServiceTypeInfoRow row = m_ServiceInfoSet.ServiceTypeInfo.NewServiceTypeInfoRow();
            string strServiceTypeKey = "";

            foreach (XmlNode childNode in node)
            {
                if (childNode.Name == "Name")
                {
                    row.ServiceTypeName = childNode.Attributes.GetNamedItem("value").Value; ;
                }
                else if (childNode.Name == "key")
                {
                    row.ServiceTypeKey = childNode.Attributes.GetNamedItem("value").Value; ;
                    strServiceTypeKey = childNode.Attributes.GetNamedItem("value").Value; ;
                }
                else if (childNode.Name == "Service")
                {
                    ReadService(childNode, strServiceTypeKey);
                }
            }
            m_ServiceInfoSet.ServiceTypeInfo.AddServiceTypeInfoRow(row);
        }

        private void ReadService(XmlNode node, string strServiceTypeKey)
        {
            string strServiceKey = "";
            ServiceDataSet.ServiceInfoRow row = m_ServiceInfoSet.ServiceInfo.NewServiceInfoRow();

            foreach (XmlNode childNode in node)
            {
                if (childNode.Name == "Name")
                {
                    row.ServiceName = childNode.Attributes.GetNamedItem("value").Value;
                }
                else if (childNode.Name == "Key")
                {
                    row.ServiceKey = childNode.Attributes.GetNamedItem("value").Value;
                    strServiceKey = childNode.Attributes.GetNamedItem("value").Value;
                }
                else if (childNode.Name == "drives")
                {
                    ReadLibClass(childNode, strServiceTypeKey, strServiceKey);
                }
            }
            row.ServiceTypeKey = strServiceTypeKey;
            m_ServiceInfoSet.ServiceInfo.AddServiceInfoRow(row);
        }

        private void ReadLibClass(XmlNode node, string strServiceTypeKey, string strServiceKey)
        {
            ServiceDataSet.DriveClassInfoRow row = m_ServiceInfoSet.DriveClassInfo.NewDriveClassInfoRow();
            foreach (XmlNode childNode in node)
            {
                if (childNode.Name == "DriverID")
                {
                    row.DriverID = childNode.Attributes.GetNamedItem("value").Value;
                }
                else if (childNode.Name == "Version")
                {
                    row.Version = childNode.Attributes.GetNamedItem("value").Value;
                }
                else if (childNode.Name == "ClassName")
                {
                    row.ClassName = childNode.Attributes.GetNamedItem("value").Value;
                }
                else if (childNode.Name == "Notes")
                {
                    row.Notes = childNode.Attributes.GetNamedItem("value").Value;
                }
                else if (childNode.Name == "Create")
                {
                    row.Create = childNode.Attributes.GetNamedItem("value").Value;
                }
                else if (childNode.Name == "parameter")
                {
                    row.parameter = childNode.Attributes.GetNamedItem("value").Value;
                }
                else if (childNode.Name == "Template")
                {
                    row.Template = childNode.Attributes.GetNamedItem("value").Value;
                }
            }
            row.ServiceKey = strServiceKey;
            row.ServiceTypeKey = strServiceTypeKey;
            m_ServiceInfoSet.DriveClassInfo.AddDriveClassInfoRow(row);
        }

        #endregion

        #region 构造函数
        public DataGatwayPresenter()
        {
            GetFileRegisterInfo();
            ReadServiceInfo();
            GetConfigSetting();

            DataSet projectSet = new DataSet();

            projectSet.ReadXml(Application.StartupPath + "\\XML\\ProjectInfo.xml");
            m_StandardClassSet.ReadXml(Application.StartupPath + "\\ClassParameter.xml");

            foreach (DataRow row in projectSet.Tables["ProjectTable"].Rows)
            {
                if (Convert.ToInt32(row["Active"]) == 0)
                {
                    continue;
                }
                ServiceEntity entity = new ServiceEntity();
                entity.ProjectNO = row["ProjectNO"].ToString().Trim();
                entity.ProjectName = row["ProjectName"].ToString().Trim();
                entity.ProjectID = row["ProjectID"].ToString().Trim();

                string strFilter = string.Format("ProjectID='{0}'", row["ProjectID"].ToString().Trim());

                string strFilter2 = string.Format("ProjectID='{0}' and DelFlag=0", row["ProjectID"].ToString().Trim());

                DataRow[] rows = projectSet.Tables["ProjectDetailTable"].Select(strFilter2, "RunSeq asc");

                DataTable serviceTmpTable = new DataTable();
                serviceTmpTable = projectSet.Tables["ProjectDetailTable"].Clone();

                foreach (DataRow tmpRow in rows)
                {
                    if (Convert.ToInt32(tmpRow["Active"]) == 0)
                    {
                        continue;
                    }
                    serviceTmpTable.ImportRow(tmpRow);
                }
                serviceTmpTable.Columns.Add("LibClassName");
                serviceTmpTable.Columns.Add("BackClassName");

                foreach (DataRow tmpRow in serviceTmpTable.Rows)
                {
                    string strFilter1 = string.Format("DriverID='{0}'", tmpRow["libID"].ToString().Trim());
                    DataRow[] driveRows = m_ServiceInfoSet.DriveClassInfo.Select(strFilter1);    //libSet.Tables[0].Select(strFilter1);

                    if (driveRows.Length > 0)
                    {
                        tmpRow.BeginEdit();
                        tmpRow["LibClassName"] = driveRows[0]["ClassName"].ToString().Trim();
                        tmpRow.EndEdit();
                    }
                    if (tmpRow.IsNull("OutLibID") == false)
                    {
                        strFilter1 = string.Format("DriverID='{0}'", tmpRow["OutLibID"].ToString().Trim());
                        driveRows = m_ServiceInfoSet.DriveClassInfo.Select(strFilter1);
                        if (driveRows.Length > 0)
                        {
                            tmpRow.BeginEdit();
                            tmpRow["BackClassName"] = driveRows[0]["ClassName"].ToString().Trim();
                            tmpRow.EndEdit();
                        }
                        else
                        {
                            tmpRow.BeginEdit();
                            tmpRow["BackClassName"] = " ";
                            tmpRow.EndEdit();
                        }
                    }
                }
                serviceTmpTable.AcceptChanges();
                entity.ServiceTable = serviceTmpTable.Copy();


                DataRow[] mappingRows = projectSet.Tables["MappingTable"].Select(strFilter);
                DataTable mappingTable = projectSet.Tables["MappingTable"].Clone();

                foreach (DataRow mappingRow in mappingRows)
                {
                    mappingTable.ImportRow(mappingRow);
                }
                entity.MappingTable = mappingTable.Copy();

                DataTable ruleTmpTable = new DataTable();
                DataTable ruleDetailTable = new DataTable();

                ruleTmpTable = projectSet.Tables["DataRuleTable"].Clone();
                ruleDetailTable = projectSet.Tables["RuleDetailTable"].Clone();

                DataRow[] ruleRows = projectSet.Tables["DataRuleTable"].Select(strFilter);

                foreach (DataRow ruleTmpRow in ruleRows)
                {
                    ruleTmpTable.ImportRow(ruleTmpRow);

                    strFilter = string.Format("RuleID='{0}'", ruleTmpRow["RuleID"].ToString().Trim());

                    DataRow[] ruleDetailRows = projectSet.Tables["RuleDetailTable"].Select(strFilter);

                    foreach (DataRow detailRow in ruleDetailRows)
                    {
                        ruleDetailTable.ImportRow(detailRow);
                    }
                }
                ruleDetailTable.AcceptChanges();
                ruleTmpTable.AcceptChanges();
                entity.RuleDetailiTable = ruleDetailTable.Copy();
                entity.RuleTable = ruleTmpTable.Copy();


                strFilter = string.Format("ProjectID='{0}'", row["ProjectID"].ToString().Trim());
                DataTable nodeTable = projectSet.Tables["RuleNodeTable"].Clone();
                DataRow[] nodeRows = projectSet.Tables["RuleNodeTable"].Select(strFilter);

                foreach (DataRow nodeRow in nodeRows)
                {
                    nodeTable.ImportRow(nodeRow);
                }
                entity.RuleNodeTable = nodeTable.Copy();
                m_ServiceList.Add(entity);
            }
            Log.WriteLog("项目队列初始化完毕", 0, "项目初始化");
        }
        #endregion

        private void ExecuteExtendedBusiness(string strServiceKey, string strServiceType, SyncParameterEntity m_OutputParameterEntity,
                                             List<SyncParameterEntity> m_OutputSubentityList)
        {
            StandardDAL dal = new StandardDAL();
            ExecuteAPI exectAPI = new ExecuteAPI();

            if (m_OutputSubentityList.Count > 0)
            {
                for (int i = 0; i < m_OutputSubentityList.Count; i++)
                {
                    SyncParameterEntity tmpEntity = m_OutputSubentityList[i];

                    if (tmpEntity.ServiceKey == "Product")
                    {
                        DataSet tmpSet = dal.GetProductByVersion(tmpEntity.MainParameterName, tmpEntity.MainParameterVersion);
                        if (tmpSet.Tables[0].Rows.Count == 0)
                        {
                            DataSet tmpSet1 = dal.GetProduct(tmpEntity.MainParameterName);
                            if (tmpSet1.Tables[0].Rows.Count > 0)
                            {
                                string strVer = dal.GetProductCurrencyVersion(tmpEntity.MainParameterName);
                                OutInfoEntity infoEntity = new OutInfoEntity();
                                exectAPI.CreateRDOEntityRevision("Product", tmpEntity.MainParameterName, strVer, tmpEntity, ref infoEntity);
                            }
                            else
                            {
                                OutInfoEntity infoEntity = new OutInfoEntity();
                                exectAPI.CreateRDOEntity("Product", tmpEntity, ref infoEntity);
                            }
                        }
                    }
                    else if (tmpEntity.ServiceKey == "Spec")
                    {
                        DataSet tmpSet = dal.GetSpecInfo(tmpEntity.MainParameterVersion, tmpEntity.MainParameterName);
                        if (tmpSet.Tables[0].Rows.Count == 0)
                        {
                            DataSet tmpSet1 = dal.GetSpecInfo(tmpEntity.MainParameterName);
                            if (tmpSet1.Tables[0].Rows.Count > 0)
                            {
                                string strVer = dal.GetSpecVersion(tmpEntity.MainParameterName);
                                OutInfoEntity myEntity = new OutInfoEntity();
                                exectAPI.CreateSpecVersion(tmpEntity.MainParameterName, strVer, tmpEntity, ref myEntity);
                            }
                            else
                            {
                                OutInfoEntity myEntity = new OutInfoEntity();
                                exectAPI.CreateSpec(tmpEntity, ref myEntity);
                            }
                        }
                    }
                }
            }
            else
            {

            }
        }


        public void RunService()
        {
            try
            {
                //add:Wangjh 
                //System.Threading.Thread thPDMToOther = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
                //{
                //    try
                //    {
                //        JudgeFactoryAndSaveBlob();
                //    }
                //    catch (Exception e)
                //    {
                //        Log.WriteOrcaleError("PDMTOMES_Other" + "@^" + "集成分发失败" + e.Message.Replace("\'", "\"") + "@^" + "" + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 写入数据库        
                //    }
                //}));
                //thPDMToOther.Start();

                //do
                //{
                //    System.Threading.Thread.Sleep(100);
                //} while (thPDMToOther.ThreadState != System.Threading.ThreadState.Stopped);//线程是否完成
               
                for (int i = 0; i < m_ServiceList.Count; i++)
                {
                    ServiceEntity se = m_ServiceList[i];
                    //标准数据导入
                    FileInfoDeal(se);

                    #region 扩展信息处理
                    if (string.IsNullOrEmpty(m_MainExtendedBusiness.Trim()))
                    {
                        return;
                    }  

                    #endregion
                }
            }
            catch (Exception myError)
            {
                Log.WriteLog(myError.Message, 1, "运行异常");
                Log.WriteOrcaleError("PDMTOMES" + "@^" + myError.Message.Replace("\'", "\"") + "@^" + "" + "@^" + Convert.ToString(Guid.NewGuid()), myError);//add:Wangjh 写入数据库        
            }
        }

        private void FileInfoDeal(ServiceEntity se)
        {
            Log.SetConfig();//add:Wangjh 20170926
            List<FileEntity> fileList = CheckDataFile(se.ProjectNO);
            if (fileList.Count == 0)
            {
                return;
            }

            Log.WriteLog(se.ProjectName, 1, "执行任务");
            string strFilter = string.Format("ProjectID='{0}'", se.ProjectID);
            DataRow[] rows = se.ServiceTable.Select(strFilter);

            for (int i = 0; i < fileList.Count; i++)//增加超越单判断
            {
                //如果是超越单 add:Wangjh 20171026
                if (fileList[i].Service == "Surpass")
                {
                    try
                    {
                        Surpass sp = new Surpass();
                        sp.DataFilePath = fileList[i].FileName;
                        sp.Execute();
                        Log.WriteOrcale("PDMTOMES_Surpass" + "@^" + "超越单创建成功" + "@^" + Path.GetFileName(fileList[i].FileName) + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 写入数据库
                    }
                    catch (Exception myError)
                    {
                        Log.WriteLog(myError.Message + myError.StackTrace, 1, "标准服务导入");
                        Log.WriteOrcaleError("PDMTOMES_Surpass" + "@^" + myError.Message + "@^" + Path.GetFileName(fileList[i].FileName) + "@^" + Convert.ToString(Guid.NewGuid()), myError);//add:Wangjh 写入数据库
                    }
                    MoveFile(se.ProjectNO, fileList[i]);
                    continue;

                }
                //

                //记录件号和版本 add:Wangjh 20181218
                    string[] productInfo=m_AssistantClass.GetProductName(fileList[i].FileName);
                    m_ProductName = productInfo[0];
                    m_ProductVersion = productInfo[1];
                //


                foreach (DataRow row in rows)
                {
                    m_OutInfoList.Clear();

                    #region 第一处理节
                    if (!row.IsNull("LibClassName") && !string.IsNullOrEmpty(row["LibClassName"].ToString()))
                    {
                        try
                        { }
                        catch (Exception myError)
                        {
                            Log.WriteLog(myError.Message, 1, "前置扩展信息导入");
                        }
                    }


                    #endregion

                    string strServiceKey = row["ServiceKey"].ToString().Trim();
                    strFilter = string.Format("serviceKey='{0}'", strServiceKey);
                    DataRow[] standRows = m_StandardClassSet.Tables[0].Select(strFilter);

                    if (standRows.Length > 0)
                    {
                        DataRow standRow = standRows[0];

                        #region 标准导入
                        try
                        {
                            SyncInfterface syncFace = GetSyncObject.instance.GetObject(standRow["ClassName"].ToString().Trim());

                            syncFace.ServiceInfoEntity = se;
                            syncFace.ProjectID = se.ProjectID;
                            syncFace.LibID = row["libID"].ToString().Trim();
                            syncFace.DataFilePath = fileList[i].FileName;
                            syncFace.AccessoriesPath = m_AccessoriesPath;
                            syncFace.SyncType = m_SyncType;
                            syncFace.Execute();
                            if (syncFace.OutParameterObject != null)
                            {
                                m_OutInfoList.Add(syncFace.OutParameterObject);
                            }
                            if (syncFace.OutParameterObjectList.Count > 0)
                            {
                                for (int k = 0; k < syncFace.OutParameterObjectList.Count; k++)
                                {
                                    m_OutInfoList.Add(syncFace.OutParameterObjectList[k]);
                                }
                            }
                        }
                        catch (Exception myError)
                        {
                            Log.WriteLog(myError.Message + myError.StackTrace, 1, "标准服务导入");
                            Log.WriteOrcaleError("PDMTOMES_catch" + "@^" + myError.Message + "@^" + Path.GetFileName(fileList[i].FileName) + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_ProductName + ":" + m_ProductVersion, myError);//add:Wangjh 写入数据库
                        }
                        #endregion
                    }

                    #region 第三处理节
                    if (!row.IsNull("LibClassName") && !string.IsNullOrEmpty(row["LibClassName"].ToString()))
                    {
                        try
                        { }
                        catch (Exception myError)
                        {
                            Log.WriteLog(myError.Message, 1, "后置信息导入");
                        }
                    }

                    #endregion
                }

                try
                {
                    StepInfo stepInfo = new StepInfo();
                    stepInfo.DataFilePath = fileList[i].FileName;
                    stepInfo.Execute();
                }
                catch (Exception myError)
                {
                    Log.WriteLog(myError.Message + myError.StackTrace, 1, "StepInfo标准服务导入");
                    Log.WriteOrcale("PDMTOMES_StepInfo" + "@^" + myError.Message + "@^" + Path.GetFileName(fileList[i].FileName) + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_ProductName + ":" + m_ProductVersion);//add:Wangjh 写入数据库
                }

                try
                {   //检测项处理
                    Checks ck = new Checks();
                    ck.DataFilePath = fileList[i].FileName;
                    ck.Execute();
                }
                catch (Exception myError)
                {
                    Log.WriteLog(myError.Message + myError.StackTrace, 1, "Checks标准服务导入");
                    Log.WriteOrcale("PDMTOMES_Check" + "@^" + myError.Message + "@^" + Path.GetFileName(fileList[i].FileName) + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_ProductName + ":" + m_ProductVersion);//add:Wangjh 写入数据库
                }

                try
                {
                    Tools tool = new Tools();
                    tool.DataFilePath = fileList[i].FileName;
                    tool.Execute();
                }
                catch (Exception myError)
                {
                    Log.WriteLog(myError.Message + myError.StackTrace, 1, "Tools标准服务导入");
                    Log.WriteOrcale("PDMTOMES_Tools" + "@^" + myError.Message + "@^" + Path.GetFileName(fileList[i].FileName) + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_ProductName + ":" + m_ProductVersion);//add:Wangjh 写入数据库
                }
               
                MoveFile(se.ProjectNO, fileList[i]);
            }

           // MoveFile(se.ProjectNO, fileList);
        }

        private void MoveFile(string strProjectNO, List<FileEntity> fileList)
        {
            DataSet FileSet = new DataSet();

            if (File.Exists(Application.StartupPath + "\\XML\\registerFile.xml") == true)
            {
                FileSet.ReadXml(Application.StartupPath + "\\XML\\registerFile.xml");
            }
            else
            {
                DataTable registerXmlTable = new DataTable();
                registerXmlTable.Columns.Add("xmlFile");
                registerXmlTable.Columns.Add("ProjectNO");
                registerXmlTable.Columns.Add("ServiceKey");
                registerXmlTable.Columns.Add("CreateDate");
                FileSet.Tables.Add(registerXmlTable);
            }

            for (int i = 0; i < fileList.Count; i++)
            {
                XmlDocument myxml = new XmlDocument();
                myxml.Load(fileList[i].FileName);
                if (myxml.DocumentElement == null)
                {
                    return;
                }
                XmlNode stu = myxml.DocumentElement;
                string strFilePojectNO = "";
                string strService = "";
                string strCreateDate = "";
                string strProductName = "";
                try {
                    foreach (XmlNode node in stu.ChildNodes)
                    {
                        if (node.Name == "ProjectNO")
                        {
                            strFilePojectNO = node.InnerText;
                        }
                        if (node.Name == "Service")
                        {
                            strService = node.InnerText;
                        }
                        if (node.Name == "CreateDate")
                        {
                            strCreateDate = node.InnerText;
                        }
                        //if (node.Name == "product")//add:Wangjh 20181029
                        //{
                        //    try { strProductName = node.SelectSingleNode("item/ae8_drawingNo").InnerText; }
                        //    catch (Exception ex) { strProductName = node.SelectSingleNode("item/ly2drawingNo").InnerText; }
                        //}

                    }
                }
                catch (Exception ex) {
                    Log.WriteLog(ex.Message , 0, "备份文件报错，可能文件结构缺失");
                    Log.WriteOrcale("PDMTOMES_" + "@^" + ex.Message + "@^" + Path.GetFileName(fileList[i].FileName) + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_ProductName + ":" + m_ProductVersion);//add:Wangjh 写入数据库
                }
                if (strFilePojectNO != strProjectNO)
                {
                    continue;
                }
                int intIndex = fileList[i].FileName.LastIndexOf("\\");
                string strFileName = fileList[i].FileName.Substring(intIndex + 1);
                //yuxj20221118 增加逻辑
                StandardDAL m_dal = new StandardDAL();
                if (m_dal.CheckCamstarConnectError(strFileName))
                {
                    continue;
                }

                DataRow newRow = FileSet.Tables[0].NewRow();
                newRow["xmlFile"] = strFileName;
                newRow["ProjectNO"] = strFilePojectNO;
                newRow["CreateDate"] = strCreateDate;
                FileSet.Tables[0].Rows.Add(newRow);
                FileSet.WriteXml(Application.StartupPath + "\\XML\\registerFile.xml");
                string strTmp = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().Trim() + DateTime.Now.Day.ToString() +
                                DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
                File.Copy(fileList[i].FileName, Application.StartupPath + "\\XML\\Back\\" +  strFileName + strTmp + ".bck");
                File.Delete(fileList[i].FileName);
            }
        }

        private void MoveFile(string strProjectNO,FileEntity file)
        {
            DataSet FileSet = new DataSet();

            if (File.Exists(Application.StartupPath + "\\XML\\registerFile.xml") == true)
            {
                FileSet.ReadXml(Application.StartupPath + "\\XML\\registerFile.xml");
            }
            else
            {
                DataTable registerXmlTable = new DataTable();
                registerXmlTable.Columns.Add("xmlFile");
                registerXmlTable.Columns.Add("ProjectNO");
                registerXmlTable.Columns.Add("ServiceKey");
                registerXmlTable.Columns.Add("CreateDate");
                FileSet.Tables.Add(registerXmlTable);
            }
            XmlDocument myxml = new XmlDocument();
            myxml.Load(file.FileName);
            if (myxml.DocumentElement == null)
            {
                return;
            }
            XmlNode stu = myxml.DocumentElement;
            string strFilePojectNO = "";
            string strService = "";
            string strCreateDate = "";
            string strProductName = "";
            try
            {
                foreach (XmlNode node in stu.ChildNodes)
                {
                    if (node.Name == "ProjectNO")
                    {
                        strFilePojectNO = node.InnerText;
                    }
                    if (node.Name == "Service")
                    {
                        strService = node.InnerText;
                    }
                    if (node.Name == "CreateDate")
                    {
                        strCreateDate = node.InnerText;
                    }
                    //if (node.Name == "product")//add:Wangjh 20181029
                    //{
                    //    try { strProductName = node.SelectSingleNode("item/ae8_drawingNo").InnerText; }
                    //    catch (Exception ex) { strProductName = node.SelectSingleNode("item/ly2drawingNo").InnerText; }
                    //}

                }
            }
            catch (Exception ex)
            {
                Log.WriteLog(ex.Message, 0, "备份文件报错，可能文件结构缺失");
                Log.WriteOrcale("PDMTOMES_" + "@^" + ex.Message + "@^" + Path.GetFileName(file.FileName) + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_ProductName + ":" + m_ProductVersion);//add:Wangjh 写入数据库
            }
            if (strFilePojectNO != strProjectNO)
            {
                return ;
            }
            int intIndex = file.FileName.LastIndexOf("\\");
            string strFileName = file.FileName.Substring(intIndex + 1);

            //yuxj20221118 增加逻辑,如果是camstar报错不移动
            StandardDAL m_dal = new StandardDAL();
            if (m_dal.CheckCamstarConnectError(strFileName))
            {                
                return;
            }

            DataRow newRow = FileSet.Tables[0].NewRow();
            newRow["xmlFile"] = strFileName;
            newRow["ProjectNO"] = strFilePojectNO;
            newRow["CreateDate"] = strCreateDate;
            FileSet.Tables[0].Rows.Add(newRow);
            FileSet.WriteXml(Application.StartupPath + "\\XML\\registerFile.xml");
            string strTmp = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().Trim() + DateTime.Now.Day.ToString() +
                            DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
            File.Copy(file.FileName, Application.StartupPath + "\\XML\\Back\\" + strFileName + strTmp + ".bck");
            File.Delete(file.FileName);
        }

        private List<FileEntity> CheckDataFile(string projectNO)
        {
            List<FileEntity> fileList = new List<FileEntity>();
            bool isOk = false;
            string strPath = m_strDataXml; //Read("DataXmlPath", out isOk);
            DirectoryInfo mydir = new DirectoryInfo(strPath);

            //add:Wangjh 20220829 按文件创建时间正序处理
            var fss = mydir.GetFileSystemInfos();
            Array.Sort(fss, (fi1, fi2) =>
            {   
                //按修改时间正序
                return fi1.LastWriteTime.CompareTo(fi2.LastWriteTime);
            });
            //

            //JudgeFactoryAndSaveBlob();//增加机匣分厂判断并写入数据 add:Wanjh 20170928

            foreach (FileSystemInfo fsi in mydir.GetFileSystemInfos())
            {
                if (Path.GetExtension(fsi.FullName).ToUpper() != ".XML")
                {
                    continue;
                }
                //当前时间-最后修改时间<一秒之内先不处理，不然会出现进程占用情况 add:Wangjh 20220829
                if ((DateTime.Now - fsi.LastWriteTime).TotalSeconds<1) {
                    continue;
                }

                XmlDocument myxml = new XmlDocument();
                //addWangjh 增加文件有问题处理,防止不处理后续文件 20180103
                try
                {
                    myxml.Load(fsi.FullName);
                }
                catch (Exception myError)
                {
                    //如果是错误文件，则移动到error文件夹

                    string dir = "D:\\xml\\Error";
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                    File.Copy(fsi.FullName, dir+"\\" + fsi.Name,true);
                    File.Delete(fsi.FullName);
                    //
                    Log.WriteOrcaleError("PDMTOMES" + "@^" + myError.Message.Replace("\'", "\"") + "@^" + "" + "@^" + Convert.ToString(Guid.NewGuid()), myError);//add:Wangjh 写入数据库 
                    continue;
                }
                //
                if (myxml.DocumentElement == null)
                {
                    continue;
                }
                XmlNode stu = myxml.DocumentElement;
                string strPojectNO = "";
                string strService = "";
                string strCreateDate = "";

                foreach (XmlNode node in stu.ChildNodes)
                {
                    if (node.Name == "ProjectNO")
                    {
                        strPojectNO = node.InnerText;
                        continue;
                    }
                    if (node.Name == "Service")
                    {
                        strService = node.InnerText;
                        continue;
                    }
                    if (node.Name == "CreateDate")
                    {
                        strCreateDate = node.InnerText;
                        continue;
                    }
                }
                if (strPojectNO != projectNO)
                {
                    continue;
                }
                if (m_SyncType == "1" && strService.Trim() == "")
                {
                    continue;
                }
                
                string strFilter = string.Format("xmlFile='{0}' and ProjectNO='{1}' and CreateDate='{2}'", fsi.Name, strPojectNO, strCreateDate);

                DataRow[] rows = m_FileSet.Tables[0].Select(strFilter);

                //yuxj20221118修改 相同文件名的文件可以再次处理
                //已经处理的文件还可以再次处理
                //if (rows.Length == 0)
                //{
                    FileEntity entity = new FileEntity();
                    entity.FileName = fsi.FullName;
                    entity.Service = strService;//add:Wangjh 20171026
                    fileList.Add(entity);
                //}
            }
            return fileList;
        }

        private List<FileEntity> GetExDataFile(string projectNO)
        {
            List<FileEntity> fileList = new List<FileEntity>();
            bool isOk = false;
            string strPath = m_strDataXml; //Read("DataXmlPath", out isOk);
            DirectoryInfo mydir = new DirectoryInfo(strPath);
            foreach (FileSystemInfo fsi in mydir.GetFileSystemInfos())
            {
                XmlDocument myxml = new XmlDocument();
                myxml.Load(fsi.FullName);
                if (myxml.DocumentElement == null)
                {
                    continue;
                }
                XmlNode stu = myxml.DocumentElement;
                string strPojectNO = "";
                string strService = "";
                string strCreateDate = "";


                foreach (XmlNode node in stu.ChildNodes)
                {
                    if (node.Name == "ProjectNO")
                    {
                        strPojectNO = node.InnerText;
                    }
                    if (node.Name == "Service")
                    {
                        strService = node.InnerText;
                    }
                    if (node.Name == "CreateDate")
                    {
                        strCreateDate = node.InnerText;
                    }
                }
                if (strPojectNO != projectNO)
                {
                    continue;
                }
                if (m_SyncType == "1" && strService.Trim() == "")
                {
                    continue;
                }
                string strFilter = string.Format("xmlFile='{0}' and ProjectNO='{1}' and CreateDate='{2}'", fsi.Name, strPojectNO, strCreateDate);

                DataRow[] rows = m_FileSet.Tables[0].Select(strFilter);

                if (rows.Length == 0)
                {
                    FileEntity entity = new FileEntity();
                    entity.FileName = fsi.FullName;
                    fileList.Add(entity);
                    Log.WriteLog(fsi.FullName, 0, "获取数据导入文件名");
                }
            }
            return fileList;
        }

        private void AXDataBaseDeal()
        {
            //try
            //{
            //    System.Threading.Thread td1 = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
            //    {
            //        IGatewayBuessiness dalextended = ExtendedObjectContext.instance.GetObject("AXInventTask");
            //        dalextended.InputSubentityList = m_OutInfoList;
            //        dalextended.PrefixExecute();
            //    }));
            //    td1.Start();
            //    System.Threading.Thread td2 = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
            //    {
            //        IGatewayBuessiness dalextended = ExtendedObjectContext.instance.GetObject("AXEquipment");
            //        dalextended.InputSubentityList = m_OutInfoList;
            //        dalextended.PrefixExecute();
            //    }));
            //    td2.Start();
            //    System.Threading.Thread td3 = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
            //    {
            //        IGatewayBuessiness dalextended = ExtendedObjectContext.instance.GetObject("AXItemArrivalLine");
            //        dalextended.InputSubentityList = m_OutInfoList;
            //        dalextended.PrefixExecute();
            //        dalextended.PostpositionExecute();
            //    }));
            //    td3.Start();

            //    System.Threading.Thread td4 = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
            //    {
            //         string strPath = m_strDataXml; //Read("DataXmlPath", out isOk);
            //         DirectoryInfo mydir = new DirectoryInfo(strPath);
            //         foreach (FileSystemInfo fsi in mydir.GetFileSystemInfos())
            //         {
            //             if (Path.GetExtension(fsi.FullName).ToUpper() != ".XML")
            //             {
            //                 continue;
            //             }
            //             IGatewayBuessiness dalextended = ExtendedObjectContext.instance.GetObject("ResourceInBy7103");
            //             dalextended.StrDataSource = fsi.FullName;
            //             dalextended.PrefixExecute();
            //         }
            //    }));
            //    td4.Start();

            //    do
            //    {
            //        System.Threading.Thread.Sleep(1);
            //    }
            //    //while (td4.IsAlive);  
            //    while (td1.IsAlive || td2.IsAlive || td3.IsAlive || td4.IsAlive); 
            //}
            //catch (Exception myError)
            //{
            //    Log.WriteLog(myError.Message + myError.StackTrace, 1, "前置AX数据导入");
            //}
        }

        #region 增加机匣判断并写入到机匣验证服务器中 add:Wangjh 20170928
        /// <summary>
        /// 判断是否是机匣工厂并远程写入文件到机匣验证服务器
        /// add：Wangjh 20170928
        /// </summary>
        /// <param name="mydir"></param>
        /// <returns></returns>
        void JudgeFactoryAndSaveBlob()
        {
            Log.SetConfig();
            DirectoryInfo mydir = new DirectoryInfo(m_strDataXml);
            // int IsOtherFactory = 0;//是否是其他分厂的0不是，1是
            List<FileInfo> xmlFile = new List<FileInfo>();
            List<string> documentList = new List<string>();//存放所有机匣引用的XML
            foreach (FileInfo fi in mydir.GetFiles())
            {
                if (Path.GetExtension(fi.FullName).ToUpper() != ".XML")
                {
                    continue;
                }
                XmlDocument myxml = new XmlDocument();
                myxml.Load(fi.FullName);
                if (myxml.DocumentElement == null)
                {
                    continue;
                }

                XmlElement root = myxml.DocumentElement;
                string factory = "";
                string serviceName = root.SelectSingleNode("/Root/Service").InnerText;
                if (serviceName == "Surpass")//如果是超越单则跳出
                    continue;
                try
                {

                    XmlNode workFlowNode = root.SelectSingleNode("/Root/WorkFlow/MEProcesss/MEProcess");
                    factory = workFlowNode.SelectSingleNode("ly2plant").InnerText;
                    if (!factory.Contains("601"))//("机匣"))
                    {
                        continue;
                    }
                    //获取工艺上的附件信息
                    XmlNode Documents;
                    Documents = root.SelectSingleNode("/Root/WorkFlow/MEProcesss/MEProcess/Documents");
                    foreach (XmlNode fileName in Documents.ChildNodes)
                    {
                        if (fileName.Name != "FileName") continue;
                        try { documentList.Add(fileName.InnerText); }
                        catch (Exception ex) { }
                    }

                }
                catch (Exception ex) { }
                //获取工序上的所有附件信息
                XmlNode meops = root.SelectSingleNode("/Root/WorkFlow/MEOPs");
                foreach (XmlNode meop in meops.ChildNodes)
                {
                    XmlNode Documents = meop.SelectSingleNode("Documents");
                    try
                    {
                        foreach (XmlNode fileName in Documents.ChildNodes)
                        {
                            if (fileName.Name != "FileName") continue;
                            try { documentList.Add(fileName.InnerText); }
                            catch (Exception ex) { }
                        }

                    }
                    catch (Exception ex) { }

                }

                xmlFile.Add(fi);
            }


            if (xmlFile.Count > 0)
            {
                //存入附件
                mydir = new DirectoryInfo(m_AccessoriesPath);
                foreach (string fiName in documentList)
                {
                    FileInfo fi = new FileInfo(m_AccessoriesPath + "\\" + fiName);
                    try { SaveBlobData(fi, 1); }//存入附件
                    catch (Exception ex) { }
                }

                foreach (FileInfo fi in xmlFile)
                {
                    SaveBlobData(fi, 0);//存入XML文件
                    Log.WriteOrcale("PDMTOMES_Other" + "@^" + "集成分发成功" + "@^" + fi.Name + "@^" + Convert.ToString(Guid.NewGuid()));//add:Wangjh 写入数据库   
                }
            }

        }
        /// <summary>
        /// 将获取的文件以blob的形式存入数据库中
        /// </summary>
        /// <returns></returns>
        Boolean SaveBlobData(FileInfo fi, int type)
        {
            //插入
            string insertBlobSql = @" INSERT INTO documentSave(documentSaveID,documentBlob,createdate,documentName,filetype,ISTRANSFER) VALUES(:documentSaveID,:documentBlob,SYSDATE,:documentName,:filetype,0) ";
            OracleParameter[] insertParam = new OracleParameter[4];

            //转化文件流
            FileStream fs = fi.OpenRead();
            byte[] MyData = new byte[fs.Length];
            fs.Read(MyData, 0, System.Convert.ToInt32(fs.Length));
            fs.Close();

            insertParam[0] =OracleHelper.NewOracleParameter (":documentSaveID",Guid.NewGuid().ToString(),OracleType.VarChar);
            insertParam[1] = OracleHelper.NewOracleParameter(":documentBlob", MyData, OracleType.Blob);
            insertParam[2] = OracleHelper.NewOracleParameter(":documentName", fi.Name, OracleType.VarChar);
            insertParam[3] = OracleHelper.NewOracleParameter(":filetype", type, OracleType.Number);

            int i = OracleHelper.ExecuteSql(insertBlobSql, insertParam);

            return true;
        }
        #endregion
    }

    public class FileEntity
    {
        public string FileName;
        public string Service;
    }
}
